package com.benmei.weike.web;

import com.benmei.weike.common.Lang;
import com.benmei.weike.dao.WebsiteConfigDao;
import com.benmei.weike.dto.*;
import com.benmei.weike.dto.weikeContentResponse.WeikeContentResponse;
import com.benmei.weike.dto.weikeDetailResponse.WeikeDetailResponse;
import com.benmei.weike.entity.CompositeCourse;
import com.benmei.weike.entity.MembNewUserScholarship;
import com.benmei.weike.entity.WeikeTodayBoutique;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.service.*;
import com.benmei.weike.service.common.MemcachedService;
import com.benmei.weike.util.IPUtil;
import com.benmei.weike.util.JsonUtil;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生端 微课接口
 */
@RestController
@RequestMapping(value = "/v4.2/student")
public class WeikeStudentController {

    public static final Logger logger = LoggerFactory.getLogger(WeikeStudentController.class);

    @Autowired
    private MemcachedService memcachedService;

    @Autowired
    private WeikeService weikeService;

    @Autowired
    private WeikeCommentsService weikeCommentsService;

    @Autowired
    private CompositeCourseService compositeCourseService;

    @Autowired
    private MembNewUserScholarshipService membNewUserScholarshipService;

    //log 记录方法入惨的前缀
    private static final String prefix_in = "\nparameters in -->> ";
    //log 记录方法出惨的前缀
    private static final String prefix_out = "\nparameters out -->>";

    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET})
    public String hello() {
        logger.info("hello");
        return "hello world";
    }

    /**
     * 接口编号：1 微课 -> 首页
     *
     * @return
     */
    @RequestMapping(value = "/find/index", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindIndex( @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in);
            Integer memb_id = 0;
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isNotBlank(token)) {
                Object o = memcachedService.get(token);
                if (o != null && TdNtMember.class.isInstance(o)){
                    TdNtMember tdNtMember = (TdNtMember) o;
                    memb_id = tdNtMember.getMemb_id();
                }
            }

            // 1. 今日精选 （3条数据，微课加直播）
            logger.info("\n ----------- 1. 今日精选 （3条数据，微课加直播）--------------");
            //List<CompositeCourse> todayBoutiqueList = compositeCourseService.studentFindAllCourseForTodayBoutique();
            List<WeikeTodayBoutique> todayList = weikeService.studentFindAllCourseForTodayBoutique(memb_id);
            // 2. 最热微课（3条数据）
            logger.info("\n ----------- 2. 最热微课（3条数据）--------------");
            List<WeikeBoutiqueListDto> hotWeikeList = weikeService.hotWeikeTop3(memb_id);

            // 3. 最热公开课（3条数据）
            //   logger.info("\n ----------- 3. 最热公开课（3条数据）--------------");
            //   List<HotLiveDto> hotLiveList = weikeService.hotLiveTop3();

            // 4. 全部微课(10条数据)
            logger.info("\n ----------- 4. 全部课程(10条数据) --------------");
            //   List<CompositeCourse> allCourseList = compositeCourseService.studentFindAllCourseTop10();
            PageResponse weikeList = weikeService.getWeikeTop10(memb_id);

            logger.info("\n ----------- 首页数据查询结束 --------------\n");
            Map<String, Object> obj = new HashedMap();


            WeikeVipUrl weikeVipUrl = weikeService.getVipUrl();

            obj.put("vipUrl",weikeVipUrl.getVip_url()); //成为会员图片
            obj.put("vipIntroLink", weikeVipUrl.getVip_link_url());//引导购买会员（即订阅模式），点击跳转会员说明详情H5

            obj.put("todayBoutique", todayList);
            obj.put("hotWeike", hotWeikeList);
            //   obj.put("hotLive", hotLiveList);
            obj.put("weikeList", weikeList);

            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(obj);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：2 微课 -> 分页分类查询所有微课信息（也可以查询全部微课信息）
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/find/weike", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo findCourse(@RequestBody StudentFindAllCoursePageRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));
            Integer memb_id = 0;
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isNotBlank(token)) {
                Object o = memcachedService.get(token);
                if (o != null && TdNtMember.class.isInstance(o)){
                    TdNtMember tdNtMember = (TdNtMember) o;
                    memb_id = tdNtMember.getMemb_id();
                }
            }
            PageResponse response = weikeService.getAllCourse(req,memb_id);
            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(response);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：3 发现 -> 微课精选 （其实是查询全部的微课）
     *
     * @return
     */
    @RequestMapping(value = "/boutique/list", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo WeikeBoutiqueList(@RequestBody PageRequest pageRequest) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(pageRequest));

            PageResponse obj = weikeService.weikeBoutiqueList(pageRequest);

            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(obj);

            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：4 发现 --> 今日精选 --> 全部（最多10条数据）
     *
     * @return
     */
    @RequestMapping(value = "/find/today-boutique/all", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindAllCourseForTodayBoutiqueAll(@RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in);
            Integer memb_id = 0;
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isNotBlank(token)) {
                Object o = memcachedService.get(token);
                if (o != null && TdNtMember.class.isInstance(o)){
                    TdNtMember tdNtMember = (TdNtMember) o;
                    memb_id = tdNtMember.getMemb_id();
                }
            }
            List<CompositeCourse> list = compositeCourseService.studentFindAllCourseForTodayBoutiqueAll(memb_id);

            RetInfo retInfo = RetInfo.getSuccessInfo(list);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：5 发现 -> 最热微课 - 查看全部
     *
     * @return
     */
    @RequestMapping(value = "/hot/list", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo WeikeHotList(@RequestBody PageRequest pageRequest,@RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(pageRequest));
            Integer memb_id = 0;
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isNotBlank(token)) {
                Object o = memcachedService.get(token);
                if (o != null && TdNtMember.class.isInstance(o)){
                    TdNtMember tdNtMember = (TdNtMember) o;
                    memb_id = tdNtMember.getMemb_id();
                }
            }
            PageResponse obj = weikeService.weikeHotList(pageRequest,memb_id);

            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(obj);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：6 微课详情
     * <p>
     * detail包含以下内容：老师信息，封面图片，微课介绍，微课标题和语音时长，微课评价及老师的回复
     * 微课detail 和 微课content不同，contetn是微课的教学内容：ppt、语音和文本
     * </p>
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/find/detail", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindWeikeDetail(@RequestBody WeikeFindContentRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入惨
            logger.info(prefix_in + JsonUtil.toJson(req));

            //学生不登录也可以查看课程详
            Integer memb_id = getMemberIdByToken(token);

            //校验 业务参数
            String weike_id_str = req.getWeike_id();
            if (StringUtils.isBlank(weike_id_str)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            if (!StringUtils.isNumeric(weike_id_str)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' must be numeric");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Long weike_id = Long.parseLong(weike_id_str);


            //处理业务
            WeikeDetailResponse respons = weikeService.getWeikeDetail(memb_id, weike_id);

            //创建返回消息，并打印日志
            RetInfo retInfo = RetInfo.getSuccessInfo(respons);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }

    /**
     * 接口编号：7 查询评论
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/find/comments", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindComments(@RequestBody FindCommentsPageRequest req) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));

            //校验 业务参数
            Long weike_id = req.getWeike_id();
            if (weike_id == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' is required");
                return retInfo;
            }
            PageResponse response = weikeCommentsService.studentFindComments(req);

            RetInfo retInfo = RetInfo.getSuccessInfo(response);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：8 保存评论
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/token/save/comment", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentSaveComment(@RequestBody SaveCommentRequest req, @RequestHeader(value = "token") String token) {
        logger.info(prefix_in + JsonUtil.toJson(req));
        try {
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;


            //校验 业务参数
            Long weike_id = req.getWeike_id();
            if (weike_id == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' is required");
                return retInfo;
            }

            weikeCommentsService.save(req, tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo();
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


    /**
     * 接口编号：9 微课内容content
     * 微课content 和 微课detail不同，contetn是微课的教学内容，包含：ppt、语音和文本
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/token/find/content", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindWeikeContent(@RequestBody WeikeFindContentRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;


            //校验 业务参数
            String weike_id_str = req.getWeike_id();
            if (StringUtils.isBlank(weike_id_str)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' is required");
                logger.info(prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            if (!StringUtils.isNumeric(weike_id_str)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'weike_id' must be numeric");
                logger.info(prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Long weike_id = Long.parseLong(weike_id_str);

            //处理业务
            WeikeContentResponse respons = weikeService.getWeikeContent(tdNtMember.getMemb_id(), weike_id);

            RetInfo retInfo = RetInfo.getSuccessInfo(respons);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


    /**
     * 接口编号：10 创建微课订单
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/token/create/order/Deprecated", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentCreateOrder(HttpServletRequest request, @RequestBody StudentCreateOrderRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));
            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            //校验 业务参数
            Long weike_id = req.getWeike_id();
            if (weike_id == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("weike_id不能为空");
                logger.info(JsonUtil.toJson(retInfo) + " weike_id:" + weike_id);
                return retInfo;
            }

            String channel = req.getChannel();
            if (StringUtils.isBlank(channel)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("支付方式不能为空");
                logger.info(JsonUtil.toJson(retInfo) + " channel:" + channel);
                return retInfo;
            }

            Map<String, Object> map = weikeService.studentCreateOrder(req, tdNtMember.getMemb_id(), IPUtil.getIp(request));

            RetInfo retInfo = RetInfo.getSuccessInfo("订单创建成功");
            retInfo.setObj(map);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            logger.error(e.getMessage(), e);
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


    /**
     * 接口编号：11 购买微课（付款）
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/token/payment", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentPayment(@RequestBody StudentPaymentRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            //校验 业务参数
            Long weikeId = req.getWeike_id();
            if (weikeId == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("微课id不能为空");
                return retInfo;
            }

            weikeService.studentPayment(req, tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo("购买微课成功");
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：12 老师详情 -> 微课列表
     *
     * @return
     */
    @RequestMapping(value = "/find/list/for/teacher", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentWeikeListForTeacher(@RequestBody StudentFindWeikeListForTeacherPageRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));
            //参数校验
            if (req.getTea_id() == null) {
                return RetInfo.getClientErrorInfo("Parameter 'tea_id' is required");
            }
            PageResponse obj = weikeService.studentWeikeListForTeacher(req);

            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(obj);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }

    /**
     * 接口编号：13 我 → 我的课程 → 微课
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/token/my/weike", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentMyWeike(@RequestBody PageRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            MyWeikePageResponse response = weikeService.studentMyWeike(req, tdNtMember.getMemb_id());

            // v4.3.1新增 会员信息，页面显示会员起止时间


            RetInfo retInfo = RetInfo.getSuccessInfo(response);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：14 查询学生是否购买过课程（购买课程后才能给老师发私信。因为有其他机构到我们app中，通过给发老师私信挖外教老师。）
     * <p>
     * 购买过微课和课程的都算，购买直播课不算
     *
     * @return
     */
    @RequestMapping(value = "/token/ispurchased", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentIsPurchased(@RequestHeader(value = "token") String token) {
        try {
            logger.info(prefix_in);

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            StudentIsPurchasedDto dto = weikeService.studentIsPurchased(tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo(dto);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 接口编号：14 查询学生是否购买过课程（购买课程后才能给老师发私信。因为有其他机构到我们app中，通过给发老师私信挖外教老师。）
     * <p>
     * 购买过微课和课程的都算，购买直播课不算
     *
     * @return
     */
    @RequestMapping(value = "/salesPromotion/close", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo closeSalesPromotion(@RequestBody CloseSalesPromotionRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in);

            //学生不登录也可以
            Integer memb_id = getMemberIdByToken(token);

            if (req.getSalesPromotionId() == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'salesPromotionId' is required");
                return retInfo;
            }

            if (memb_id != null) {
                weikeService.closeSalesPromotion(req, memb_id);
            } else {
                logger.warn("学生关闭促销活动，但是学生未登录，系统不做任何操作");
            }
            RetInfo retInfo = RetInfo.getSuccessInfo();
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 根据token查询学生Id，如果token无效则返回null
     *
     * @param token
     * @return
     */
    private Integer getMemberIdByToken(@RequestHeader(value = "token", required = false) String token) {
        Integer memb_id = null;
        //校验token，如果校验通过就从缓存中读取Member
        if (!StringUtils.isBlank(token)) {
            Object o = memcachedService.get(token);
            if (o != null) {
                if (TdNtMember.class.isInstance(o)) {
                    TdNtMember tdNtMember = (TdNtMember) o;
                    memb_id = tdNtMember.getMemb_id();
                }
            }
        }
        return memb_id;
    }


    @Autowired
    private WebsiteConfigDao websiteConfigDao;
    /**
     * 查询学生是否领取过新用户10元红包
     *
     * @return
     */
    @RequestMapping(value = "/searchUserScholarship", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo closeSalesPromotion(@RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in);

            // 学生不登录也可以
            Integer memb_id = getMemberIdByToken(token);

            Map<String, Object> map = new HashMap<>();
            String red_package_page = websiteConfigDao.getData(35);
            map.put("picture",red_package_page);
            if (memb_id != null) {
                MembNewUserScholarship mnu = membNewUserScholarshipService.findByMembId(memb_id);
                if (mnu != null) {
                    map.put("isGet", 1);// 领取过了
                } else {
                    map.put("isGet", 0);// 未领取
                }
            } else {
                map.put("isGet", 0);// 未领取
            }
            RetInfo retInfo = RetInfo.getSuccessInfo(map);
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * 领取新用户120元红包
     *
     * @return
     */
    @RequestMapping(value = "/token/collectUserScholarship", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo collectUserScholarship(@RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(prefix_in);

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            membNewUserScholarshipService.collectUserScholarship(tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo();
            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }


    /**
     * 领取新用户10元红包
     *
     * @return
     */
    @RequestMapping(value = "/getWeikeVipPrice", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public RetInfo getWeikeVipPrice() {
        try {
            logger.info(prefix_in);


            Double weikePrice = weikeService.findWeikeVipPrice();
            Map<String,Double> map = new HashMap<>();
            map.put("weikeVipPrice",weikePrice);

            RetInfo retInfo = RetInfo.getSuccessInfo(map);

            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    @RequestMapping(value = "/unlockWeike", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public RetInfo getWeike(@RequestBody WeikeDto req, @RequestHeader(value = "token")String token) {
        try {
            logger.info(prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (req.getId() == 0 || req.getId() == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter weike_id  can not be null");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            Integer count = weikeService.studentBuyWeike(tdNtMember.getMemb_id(),req.getId());

            RetInfo retInfo = RetInfo.getSuccessInfo(count);

            logger.info(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

}
